<template>
  <div class="materielList">
    <div style="display: flex">
      <jc-button
        :btn-arr="['reload', 'copy', bomCost('material:save') && 'newy', 'remove', allots && 'allocation', 'option', 'sub', 'pass']"
        :disab-arr="['close', 'cancel', 'com1', 'com2', 'chart']"
        @refresh="getMaterialList"
        @newly="addMateril"
        @copyDa="copyMater"
        @audit="auditer(1)"
        @noAudit="auditer(2)"
        @submit="materSub(1)"
        @noSubmit="materSub(2)"
        @forbidden="using(1)"
        @startUsing="using(2)"
        @freeze="freeze(1)"
        @refreezing="freeze(2)"
        @del="deleteMater"
        @allot="allotVis=true"
        @toExcel="handleExport"
      />
      <el-button style="margin-left: 10px;" size="mini" type="primary" @click="isMaterReload=true">{{ $t('market.marterReload') }}</el-button>
      <el-button style="margin-left: 10px;" size="mini" type="primary" @click="isSetingCorect=true">批改</el-button>
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="searchMaterialList"
        />
        <el-button
          type="primary"
          size="mini"
          class="btn"
          @click="searchMaterialList"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          class="btn_spacing"
          :ftype="ftype"
          :msg="tacitly"
          :table-header="tableHeader1"
          :detail-header="materialTableHeader"
          :select-data="selectData"
          @seachData="searchMaterialList"
        />
      </div>
    </div>
    <div class="mainPage">
      <div class="left-mainPage">
        <el-tree
          ref="my-tree"
          node-key="id"
          highlight-current
          :data="materialGroupL"
          :props="defaultProps"
          :current-node-key="currentNodeKey"
          :default-expanded-keys="[0]"
          accordion
          @node-click="handleNodeClick"
        />
      </div>
      <div class="right-mainPage">
        <jc-table
          sortable
          :table-header="materialTableHeader"
          :table-data="materialTableData"
          :table-height="tableHeight"
          table-selection
          get-row-keys="fnumber"
          @selectionChange="selectionData"
          @clickRow="jumpMateriel"
        >
          <template v-slot:billSlot="col">
            <el-image
              class="productImg"
              :src="col.scope.row.fimg"
              :preview-src-list="[col.scope.row.fimg]"
              lazy
              scroll-container=".el-table__body-wrapper"
            />
          </template>
          <template v-slot:orderSlot="col">
            <el-link type="primary" @click="jumpMateriel(col.scope.row)">
              {{ col.scope.row.fnumber }}
            </el-link>
          </template>
          <!--审核状态-->
          <template v-slot:btnState="col">
            <el-tag
              :type="col.scope.row.stateColor"
            >
              {{ col.scope.row.fdocumentStatus }}
            </el-tag>
          </template>
          <!--禁用状态-->
          <template v-slot:tagSlot="clo">
            <el-tag v-if="clo.scope.row.fforbidStatus === 'A'">
              {{ $t('market.no') }}<!--否-->
            </el-tag>
            <el-tag v-else type="danger">
              {{ $t('market.yes') }}<!--是-->
            </el-tag>
          </template>
          <template v-slot:btnStates="clo">
            <el-tag v-if="clo.scope.row.frozenstatus === 'A'">
              {{ $t('market.normal') }}<!--正常-->
            </el-tag>
            <el-tag v-else type="danger">
              {{ $t('market.freeze') }}<!--冻结-->
            </el-tag>
          </template>
          <!--常规物料-->
          <template v-slot:text2Slot="col">
            <el-tag v-if="col.scope.row.froutine">{{ $t('market.yes') }}</el-tag>
            <el-tag v-else type="danger">{{ $t('market.no') }}</el-tag>
          </template>
        </jc-table>
        <div class="footer">
          <jc-pagination
            :total="total"
            :page.sync="pagination.pageNum"
            :limit.sync="pagination.pageSize"
            @pagination="getMaterialList"
          />
        </div>
      </div>
    </div>
    <!--    分配-->
    <el-dialog
      v-dialogDrag
      :title="$t('btn.allocation')"
      :visible.sync="allotVis"
      width="400px"
      top="5vh"
      :close-on-click-modal="false"
      close-on-press-escape
      center
    >
      <el-radio-group v-model="target">
        <el-radio :label="0">{{ $t('market.mlg') }}</el-radio>
        <el-radio :label="1">{{ $t('market.jxnx') }}</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="allotVis = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="allocation">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 物料刷新 -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.marterReload')"
      :visible.sync="isMaterReload"
      width="400px"
      top="5vh"
      :close-on-click-modal="false"
      close-on-press-escape
      center
    >
      <span>{{ $t('shop.fnumber1') }}：</span>
      <el-input v-model="materFnumber" size="mini" />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isMaterReload = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="materReload">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!--批改-->
    <setting v-if="isSetingCorect" :ftype="1" :fids="fids" @setting="getMaterialList" />
  </div>
</template>

<script>
import jcButton from '@/components/Button'
import {
  queryLargeAndMidTreeList,
  queryTBdMaterialList,
  deleteMaterial, synchronization, refreshMaterial
} from '@/api/basicManagement/materielList'
import {
  updateMaterialNotReview,
  materialAudit,
  materialSubmit,
  materialUnSubmit,
  materialUnDisable,
  materialDisable,
  materialUnRozen,
  materialRozen
} from '@/api/basicManagement/untreatedMaterie'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import { Disable, toMxAmina } from '@/components/ToMxamineState'
export default {
  name: 'MaterielList',
  components: {
    setting: () => import('@/views/basic/material/materielList/setting'),
    jcButton,
    search,
    filtration
  },
  mixins: [searData],
  data() {
    return {
      isMaterReload: false,
      isSetingCorect: false,
      materFnumber: '',
      ftype: 0,
      fbillNo: 'fnumber', // 产品描述
      materialGroupL: [{
        fname: '全部',
        id: 0,
        details: []
      }], // tree组数据
      currentNodeKey: '',
      allotVis: false,
      pagination: {
        pageNum: 1, // 当前页
        pageSize: 200 // 每页显示多少条数据
      },
      delArr: [],
      fids: [],
      total: 0, // 总条目
      materialTableHeader: [
        { label: this.$t('shop.image'), type: 'bill', prop: 'fimg', width: '100' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.createDate'), prop: 'fcreateDate' },
        { label: this.$t('market.forbidStatu'), type: 'tag', prop: 'fforbidStatus' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentStatus' },
        { label: this.$t('market.frozenstatus'), type: 'states', prop: 'frozenstatus' },
        { label: this.$t('market.froutine'), type: 'text2', prop: 'froutine' }
        // { label: this.$t('market.handle'), type: 'btn', minWidth: '80px' }
      ], // 表头数据
      materialTableData: [], // 表格数据
      defaultProps: {
        children: 'details',
        label: 'fname'
      },
      tableHeight: '75vh',
      tableHeader1: [
        { label: this.$t('market.creator'), prop: 'fcreator' },
        { label: this.$t('market.modifier'), prop: 'fmodifier' },
        { label: this.$t('market.modifyDate'), prop: 'fmodifyDate' },
        { label: this.$t('market.approver'), prop: 'fapprover' },
        { label: this.$t('market.approveDate'), prop: 'fapproveDate' },
        { label: this.$t('market.forbider'), prop: 'fforbider' },
        { label: this.$t('market.forbidDate'), prop: 'fforbidDate' },
        { label: this.$t('market.materialcost'), prop: 'fmaterialcost' },
        { label: this.$t('market.purchaseprice'), prop: 'fpurchaseprice' },
        { label: this.$t('market.averageprice'), prop: 'faverageprice' },
        { label: this.$t('market.sellingprice'), prop: 'fsellingprice' },
        { label: this.$t('market.purchasepricelast'), prop: 'fpurchasepricelast' },
        { label: this.$t('market.laborcost'), prop: 'flaborcost' },
        { label: this.$t('market.taxrate'), prop: 'ftaxrate' },
        { label: this.$t('market.weightUnit'), prop: 'fweightUnit' },
        { label: this.$t('market.width'), prop: 'fwidth' },
        { label: this.$t('market.thickness'), prop: 'fthickness' },
        { label: this.$t('market.volume'), prop: 'fvolume' },
        { label: this.$t('market.volumeUnit'), prop: 'fvolumeUnit' },
        { label: this.$t('market.suite'), prop: 'fsuite' },

        { label: this.$t('market.ferpclsId'), prop: 'ferpcls' },
        { label: this.$t('market.category'), prop: 'fcategory' },
        { label: this.$t('market.grossweight'), prop: 'fgrossweight' },
        { label: this.$t('market.height'), prop: 'fheight' },
        { label: this.$t('market.length'), prop: 'flength' },
        { label: this.$t('market.img'), prop: 'fimg' },
        { label: this.$t('market.isasset'), prop: 'fisasset' },
        { label: this.$t('market.isinventory'), prop: 'fisinventory' },
        { label: this.$t('market.isproduce'), prop: 'fisproduce' },
        { label: this.$t('market.ispurChase'), prop: 'fispurChase' },
        { label: this.$t('market.issale'), prop: 'fissale' },
        { label: this.$t('market.issubcontract'), prop: 'fissubcontract' },

        { label: this.$t('market.materialGroup'), prop: 'fmaterialGroup' },

        { label: this.$t('market.netweight'), prop: 'fnetweight' },
        { label: this.$t('market.openheight'), prop: 'fopenheight' },
        { label: this.$t('market.openlength'), prop: 'fopenlength' },
        { label: this.$t('market.openthickness'), prop: 'fopenthickness' },
        { label: this.$t('market.openvolume'), prop: 'fopenvolume' },
        { label: this.$t('market.openwidth'), prop: 'fopenwidth' },

        { label: this.$t('market.workshop'), prop: 'fworkshop' },
        { label: this.$t('market.produceUnit'), prop: 'fproduceUnit' },
        { label: this.$t('market.pickStock'), prop: 'fpickStock' },
        { label: this.$t('market.pickbinId'), prop: 'fpickbinId' },
        { label: this.$t('market.issueType'), prop: 'fissueType' },
        { label: this.$t('market.overrate'), prop: 'ffinishreceiptoverrate' },
        { label: this.$t('market.shortrate'), prop: 'ffinishreceiptshortrate' },

        { label: this.$t('market.stockUnit'), prop: 'fstoreUnit' },
        { label: this.$t('market.stock2'), prop: 'fstock' },
        { label: this.$t('market.stockplace'), prop: 'fstockplaceId' },
        { label: this.$t('market.maxStock'), prop: 'fmaxStock' },
        { label: this.$t('market.minStock'), prop: 'fminStock' },
        { label: this.$t('market.safeStock'), prop: 'fsafeStock' },

        { label: this.$t('market.storageUnit'), prop: 'fpurchaseUnit' },
        { label: this.$t('market.defaultvendor'), prop: 'fdefaultvendor' },

        { label: this.$t('market.saleUnit'), prop: 'fsaleUnit' },
        { label: this.$t('market.outStocklmth'), prop: 'foutStocklmth' },
        { label: this.$t('market.outStocklmtl'), prop: 'foutStocklmtl' },
        { label: this.$t('market.note'), prop: 'fremarks   ' }
      ],
      target: 0
    }
  },
  watch: {
    currentNodeKey(value) {
      if (value.toString()) {
        this.$refs['my-tree'].setCurrentKey(value)
      } else {
        this.$refs['my-tree'].setCurrentKey(null)
      }
    }
  },
  created() {
    this.getMaterialGroupL()
    this.getMaterialList()
    this.tableHeader1 = this.materialTableHeader.concat(this.tableHeader1)
    this.oldTabHeader = this.materialTableHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.materialTableHeader.map(res => {
          return res.label
        })
        const filterVal = this.materialTableHeader.map(res => {
          return res.prop
        })
        if (this.materialTableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryTBdMaterialList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData,
            fnumberGroup: this.currentNodeKey
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(res => {
                if (res.frozenstatus === 'A') {
                  res.frozenstatus = '正常'
                } else {
                  res.frozenstatus = '冻结'
                }
                return (toMxAmina(res), Disable(res))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '物料列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 物料刷新
    materReload() {
      const DATA = {
        fnumber: this.materFnumber
      }
      refreshMaterial(DATA).then(res => {
        if (res.code === 0) {
          this.isMaterReload = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 进入物料主数据
    jumpMateriel(ev) {
      const FNUMBER = ev.fnumber
      this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.pagination.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.getMaterialList(ev.detail)
      } else {
        this.getMaterialList()
      }
    },
    // 树形筛选
    async handleNodeClick(data) {
      this.currentNodeKey = data.fnumber
      this.getMaterialList()
    },
    // 获取物料数据
    async getMaterialList(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      this.isSetingCorect = false
      const DATA = {
        ...this.pagination,
        search: this.searCollData.concat(this.details),
        fnumberGroup: this.currentNodeKey
      }
      const { data: RES, code, message } = await queryTBdMaterialList(DATA)
      if (code === 1) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          type: 'error'
        })
        return
      }
      this.materialTableData = RES.array.map(res => {
        return toMxAmina(res)
      })
      this.total = RES.total
    },
    // 获取树型控件数据
    async getMaterialGroupL() {
      const { data: RES } = await queryLargeAndMidTreeList({})
      this.materialGroupL[0].details = RES
    },
    // 新增物料
    addMateril() {
      this.$router.push({ path: '/createMateriel2' })
    },
    // 查询物料
    detailMateriel(FNUMBER) {
      this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
    },
    // 提交
    async materSub(ev) {
      const api = ev === 1 ? materialSubmit : materialUnSubmit
      this.toExamineFun(api)
    },
    // 审核
    async auditer(ev) {
      const api = ev === 1 ? materialAudit : updateMaterialNotReview
      this.toExamineFun(api)
    },
    // 禁用反禁用
    async using(ev) {
      const api = ev === 1 ? materialDisable : materialUnDisable
      this.toExamineFun(api)
    },
    // 冻结反冻结
    async freeze(ev) {
      const api = ev === 1 ? materialRozen : materialUnRozen
      this.toExamineFun(api)
    }, // 复制物料
    copyMater() {
      this.$router.push({ name: 'CreateMateriel2', params: {
        id: this.selectFbi[0]
      }})
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectFbi }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.getMaterialList()
      })
    },
    // 多选
    selectionData(val) {
      this.delArr = []
      this.selectFbi = []
      this.fids = []
      this.val = val
      this.val.forEach(res => {
        res.fnumber && this.selectFbi.push(res.fnumber)
        this.delArr.push({ fmaterialId: res.fmaterialId })
        this.fids.push(res.fmaterialId)
      })
    },
    // 删除物料
    deleteMater() {
      this.$confirm('确定要删除物料么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = deleteMaterial
        this.toExamineFun(api)
      })
    },
    // 分配
    allocation() {
      const DATA = {
        target: this.target,
        fnumbers: this.selectFbi
      }
      synchronization(DATA).then(res => {
        if (res.code === 0) {
          this.allotVis = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.materialTableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.materialTableHeader = this.oldTabHeader
      } else {
        this.materialTableHeader = this.tableHeader1
      }
    }
  }
}
</script>

<style scoped lang="scss">
.mainPage {
  margin-top: 6px;
  display: flex;
  flex-direction: row;

  .left-mainPage {
    width: 12%;
    height: calc(100vh - 220px);
    overflow: auto;
    display: flex;
    flex-direction: column;
    border: 1px solid #ccc;
    &::-webkit-scrollbar-track-piece {
      background: #fff;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #eee;
      border-radius: 20px;
    }
  }
  .right-mainPage {
    width: 88%;
    margin-left: 10px;
  }
}
.materielList {
  @include listBom;
  display: flex;
  flex-direction: column;
  padding: 10px;
  background: #fff;
  .header {
    position: relative;
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .productImg {
    width: auto;
    height: 40px;
  }
  .el-dialog .el-dialog__body {
    text-align: center;
  }
  .image {
    max-height: 600px;
    max-width: 600px;
  }
}
</style>
